package com.dingxi.springbootinit.api;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class DeepSeekAiApi {
    @Value("${deepseek.api.key}")
    private String API_KEY;

    @Value("${deepseek.api.url}")
    private String API_URL;

//    public static void main(String[] args) {
//        try {
//            // 创建 HttpPost 请求
//            HttpPost request = new HttpPost("https://api.deepseek.com/chat/completions");
//            request.setHeader("Content-Type", "application/json");
//            request.setHeader("Authorization", "Bearer " + "sk-e991124fffba408b810b9b1f238bda00");
//
//            // 创建请求体
//            Map<String, Object> message = new HashMap<>();
//            message.put("role", "user");
//            message.put("content", "法国首都是哪");
//
//            Map<String, Object> requestMap = new HashMap<>();
//            requestMap.put("model", "deepseek-chat");
//            requestMap.put("messages", Collections.singletonList(message));
//            requestMap.put("temperature", 0.7);  // 添加 temperature 参数
//            requestMap.put("max_tokens", 100);   // 添加 max_tokens 参数
//
//            // 将 Map 转换为 JSON 字符串
//            ObjectMapper objectMapper = new ObjectMapper();
//            String jsonRequest = objectMapper.writeValueAsString(requestMap);
//
//            // 打印请求体
//            log.info("请求体: {}", jsonRequest);
//
//            // 设置请求体
//            request.setEntity(new StringEntity(jsonRequest,StandardCharsets.UTF_8));
//
//            // 发送请求
//            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
//                HttpResponse response = httpClient.execute(request);
//
//                // 获取响应状态码
//                int statusCode = response.getStatusLine().getStatusCode();
//                log.info("Response Status Code: {}", statusCode);
//
//                // 获取响应体
//                HttpEntity entity = response.getEntity();
//                if (entity != null) {
//                    String responseBody = EntityUtils.toString(entity);
//                    log.info("Response Body: {}", responseBody);
//
//                    // 解析 JSON 响应体
//                    Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
//                    if (responseMap.containsKey("choices")) {
//                        Map<String, Object> firstChoice = ((Map<String, Object>) ((java.util.List<?>) responseMap.get("choices")).get(0));
//                        Map<String, Object> messageMap = (Map<String, Object>) firstChoice.get("message");
//                        String content = (String) messageMap.get("content");
//                        log.info("DeepSeek 的回复: {}", content);
//                        System.out.println(content);
//                    } else {
//                        log.warn("未找到有效的回复内容。");
//
//                    }
//                }
//            }
//        } catch (Exception e) {
//            log.error("请求 DeepSeek API 失败", e);
//        }
//
//    }

    public String chat(String question) {
        try {
            // 创建 HttpPost 请求
            HttpPost request = new HttpPost(API_URL);
            request.setHeader("Content-Type", "application/json");
            request.setHeader("Authorization", "Bearer " + API_KEY);

            // 创建请求体
            Map<String, Object> message = new HashMap<>();
            message.put("role", "user");
            message.put("content", question);

            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("model", "deepseek-chat");
            requestMap.put("messages", Collections.singletonList(message));
            requestMap.put("temperature", 0.7);  // 添加 temperature 参数
            requestMap.put("max_tokens", 2000);   // 添加 max_tokens 参数

            // 将 Map 转换为 JSON 字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonRequest = objectMapper.writeValueAsString(requestMap);

            // 打印请求体
            log.info("请求体: {}", jsonRequest);

            // 设置请求体
            request.setEntity(new StringEntity(jsonRequest,StandardCharsets.UTF_8));

            // 发送请求
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpResponse response = httpClient.execute(request);

                // 获取响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                log.info("Response Status Code: {}", statusCode);

                // 获取响应体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String responseBody = EntityUtils.toString(entity);
                    log.info("Response Body: {}", responseBody);

                    // 解析 JSON 响应体
                    Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
                    if (responseMap.containsKey("choices")) {
                        Map<String, Object> firstChoice = ((Map<String, Object>) ((java.util.List<?>) responseMap.get("choices")).get(0));
                        Map<String, Object> messageMap = (Map<String, Object>) firstChoice.get("message");
                        String content = (String) messageMap.get("content");
                        log.info("DeepSeek 的回复: {}", content);
                        return content;
                    } else {
                        log.warn("未找到有效的回复内容。");
                        return null;
                    }
                }
            }
        } catch (Exception e) {
            log.error("请求 DeepSeek API 失败", e);
        }
        return null;
    }
}